using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace org.jawk.jrt
{
	/// <summary>
	/// Similar to StringTokenizer, except that tokens are delimited
	/// by a regular expression.
	/// </summary>
	/// <remarks>
	/// Similar to StringTokenizer, except that tokens are delimited
	/// by a regular expression.
	/// </remarks>
	public class RegexTokenizer : java.util.IEnumeration<object>
	{
		private List<string> array = new List<string>();

		private int idx = 0;

		/// <summary>Construct a RegexTokenizer.</summary>
		/// <remarks>Construct a RegexTokenizer.</remarks>
		/// <param name="input">The input string to tokenize.</param>
		/// <param name="regex_string">
		/// The regular expression deliniating tokens
		/// within the input string.
		/// </param>
		public RegexTokenizer(string input, string regex_string)
		{
            Regex r = new Regex(regex_string);
            int i = 0;
            foreach(Match m in r.Matches(input))
            {
                string elt = input.Substring(i, m.Index - i);
                array.Add(elt);
                i = m.Index + m.Length;
            }

            if(i<input.Length)
            {
                array.Add(input.Substring(i));
            }
		}

		// to satisfy the Enumeration<Object> interface
		public virtual bool HasMoreElements()
		{
			return idx < array.Count;
		}

        public virtual object NextElement()
        {
            return array[idx++];
        }
	}
}
